import { useAppDispatch } from '@/store/hooks';
import { getCode, login } from '@/store/slices/login';
import { Button, NavBar, Form, Input, Toast } from 'antd-mobile';
import { InputRef } from 'antd-mobile/es/components/input';
import { useEffect, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

import styles from './index.module.scss';

const Login = () => {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const [form] = Form.useForm();
  const inputRef = useRef<InputRef>(null);
  const [timeLeft, settimeLeft] = useState(0);
  const timeRef = useRef(-1);
  // 获取路由跳转的路径
  const location = useLocation();
  const loactionState = location.state;

  // 表单校验成功时执行
  const onFinish = async (values: {
    mobile: '13718451179';
    code: '123456';
  }) => {
    try {
      await dispatch(login(values)).unwrap();
      Toast.show({
        content: '登录成功',
        duration: 500,
        afterClose: () => {
          // 判断路由鉴权时state有没有页面 有跳转，没有 跳转到首页
          navigate(loactionState?.from ?? '/Home', { replace: true });
        },
      });
    } catch (e) {
      const error = e as { data: null; message: string };
      // console.dir(e);

      Toast.show({
        content: error.message,
      });
    }
  };
  // 发送验证码
  const onSend = () => {
    // true 有错误  false 没有错误  获取错误信息
    const error = form.getFieldError('mobile').length > 0;
    // 获取输入框的值 如果是undefined 就为空字符串
    const mobile = (form.getFieldValue('mobile') ?? '') as string;
    // 如果错误信息 有错误true 或 输入框值为空时 true   就让输入框获取焦点
    if (error || mobile.trim() === '') {
      return inputRef.current?.focus();
    }
    // 分发获取手机验证码
    dispatch(getCode(mobile));
    // 处理验证码倒计时
    settimeLeft(10);
    timeRef.current = window.setInterval(() => {
      console.log('定时器代码执行');

      settimeLeft((prev) => prev - 1);
    }, 1000);
  };
  // 监听定时器并卸载
  useEffect(() => {
    if (timeLeft === 0) clearInterval(timeRef.current);
  }, [timeLeft]);
  // 组件卸载时 清理定时器
  useEffect(() => {
    return () => {
      clearInterval(timeRef.current);
    };
  }, []);
  return (
    <div className={styles.root}>
      <NavBar></NavBar>

      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form form={form} onFinish={onFinish}>
          <Form.Item
            className="login-item"
            name="mobile"
            validateTrigger="onChange"
            rules={[
              { required: true, message: '请输入手机号码' },
              { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误' },
            ]}
          >
            <Input placeholder="请输入手机号" maxLength={11} ref={inputRef} />
          </Form.Item>

          <Form.Item
            className="login-item"
            extra={
              <span
                className="code-extra"
                onClick={timeLeft === 0 ? onSend : undefined}
              >
                {timeLeft === 0 ? '发送验证码' : `${timeLeft}s后重新发送`}
              </span>
            }
            name="code"
            rules={[
              { required: true, message: '请输入验证码' },
              { len: 6, message: '为6位数字' },
            ]}
            validateTrigger="onChange"
          >
            <Input placeholder="请输入验证码" autoComplete="off" />
          </Form.Item>

          {/* noStyle 表示不提供 Form.Item 自带的样式 */}
          <Form.Item noStyle shouldUpdate>
            {() => {
              return (
                <Button
                  block
                  type="submit"
                  color="primary"
                  className="login-submit"
                  disabled={
                    !form.isFieldsTouched(true) ||
                    !!form
                      .getFieldsError()
                      .filter(({ errors }) => errors.length).length
                  }
                >
                  登 录
                </Button>
              );
            }}
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
